#include "1.h"
#include "pool.h"

int CT1Pool::Init(int iQueue)
{
    if(IsInit()) return COMMON_ERR_INITED;

    m_iQuLenMax = iQueue;
    m_clQueue.Init(iQueue);
    return 0;
}

int CT1Pool::Recycle()
{
    Destruct();
    return Construct();
}

int CT1Pool::Start()
{
    int iRet = -1;
    // int iResult, iTmp;

    if(IsInit() == 0) SET_RET_AND_GOTO_EXIT(COMMON_ERR_UNINITED);
    if(IsRunning()) SET_RET_AND_GOTO_EXIT(COMMON_ERR_STATE);

    m_pobjThrd = new thread(Work_t, this);

    iRet = 0;
_Exit:
    return iRet;
}

int CT1Pool::IsRunning() { return m_pobjThrd != NULL; }

int CT1Pool::Stop()
{
    if(IsInit() == 0) return COMMON_ERR_UNINITED;

    if(m_pobjThrd)
    {
        m_clQueue.Clear();
        m_clQueue.Push(NULL);
        m_pobjThrd->join();
        DELETE_AND_NULL(m_pobjThrd);
    }

    return 0;
}

int CT1Pool::AddTask(IThrdTask* pobjTask) { return m_clQueue.Push(pobjTask); }

int CT1Pool::Construct()
{
    m_pobjThrd  = NULL;
    m_iQuLenMax = -1;
    return 0;
}

int CT1Pool::Destruct()
{
    Stop();
    return 0;
}

int CT1Pool::Work_t(CT1Pool* pParent) { return pParent->Work(); }

int CT1Pool::Work()
{
    int iRet = -1;
    int iResult, iTmp;
    void* pvData;
    IThrdTask* pobjTask;

    while(1)
    {
        iResult = m_clQueue.Pop(pvData, 5);
        if(iResult < 0) continue;
        if(pvData == NULL) break;

        pobjTask = (IThrdTask*)pvData;
        pobjTask->Work();

        if(pobjTask->m_pfunFin) pobjTask->m_pfunFin(pobjTask, pobjTask->m_pvArg);
    }

    iRet = 0;
_Exit:
    return iRet;
}
